package com.onepice.mlp.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.onepice.mlp.api.config.ServerConfig;
import com.onepice.mlp.api.config.UserProfile;
import com.onepice.mlp.core.service.MenuService;
import com.onepice.mlp.core.service.RoleService;
import com.onepice.mlp.core.service.SyslogService;
import com.onepice.mlp.core.service.UserService;
import com.onepice.mlp.data.entity.Menu;
import com.onepice.mlp.data.entity.Syslog;
import com.onepice.mlp.data.entity.User;
import com.onepice.mlp.utils.commom.ConvUtil;
import com.onepice.mlp.utils.commom.EncodeUtil;
import com.onepice.mlp.utils.commom.ResponseResult;
import com.onepice.mlp.utils.enums.CodeType;
import com.onepice.mlp.utils.enums.SyslogType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author FireWang
 * @date 2020/4/27 16:09
 * 登录管理
 */
@Slf4j
@AllArgsConstructor
@Controller
public class LoginController {
    //系统配置
    private ServerConfig serverConfig;

    private UserService userService;
    private SyslogService syslogService;
    private RoleService roleService;
    private MenuService menuService;

    //返回结果对象
    private static JSONObject resJson;

    /**
     * 登录页面初始化
     *
     * @return
     */
    @RequestMapping(value = "/login")
    public String logininit() {
        return "login";
    }

    /**
     * 执行登录
     *
     * @param request
     * @param account
     * @param password
     * @return
     */
    @RequestMapping(value = "/dologin")
    @ResponseBody
    public JSONObject login(HttpServletRequest request, String account, String password, String phone) {
        HttpSession session = request.getSession();
        try {
            User user;

            //根据账号或者手机号查找用户
            if (!"".equals(phone)) {
                user = userService.getUserByPhone(phone);
            } else {
                user = userService.getUserByUerName(account);
            }

            //判断账号是否能登录
            if (user == null) {
                resJson = ResponseResult.build(CodeType.FAIL, "登录失败：账号不存在！");
                return resJson;
            }
            if (!user.getPassword().equals(EncodeUtil.getPasswordMd5(password))) {
                resJson = ResponseResult.build(CodeType.FAIL, "登录失败：账号或密码错误！");
                return resJson;
            }
            if (ConvUtil.convToInt(user.getStatus()) != 1) {
                resJson = ResponseResult.build(CodeType.FAIL, "登录失败：该账号已被禁用！");
                return resJson;
            }

            //校验页面权限，没有权限直接拒绝访问，有权限则返回第一个页面序号
            String permission = ConvUtil.convToString(roleService.getById(user.getUserType()).getPermission());
            String url = "";
            if ("".equals(permission)) {
                resJson = ResponseResult.build(CodeType.FAIL, "登录失败：该账号没有权限！");
                return resJson;
            } else {
                int admin = 1;
                Menu menu;
                if (user.getUserType() != admin) {
                    String[] pageNums = permission.split(",");
                    menu = menuService.getById(ConvUtil.convToInt(pageNums[0]));
                } else {
                    List<Menu> menus = menuService.getAll();
                    menu = menus.get(0);
                }
                url = serverConfig.getRootPath() + menu.getPath();
            }

            UserProfile userProfile = new UserProfile();
            userProfile.setCurrentUserId(user.getId());
            userProfile.setCurrentUserLoginName(user.getUserName());
            userProfile.setCurrentUserRealName(user.getRealName());
            userProfile.setCurrentUserType(user.getUserType());
            userProfile.setCurrentUserstatus(1);
            userProfile.setCurrentUserLoginIp(serverConfig.getIpAddr(request));
            userProfile.setCurrentUserCompany(user.getCompany());
            userProfile.setUserPermission(user.getGroupId());
            userProfile.setRolePermission(roleService.getById(user.getUserType()).getPermission());

            //更新登录信息
            user.setLastLoginTime(new Date());
            user.setLastLoginIp(serverConfig.getIpAddr(request));
            userService.update(user);

            //添加系统日志
            Syslog syslog = Syslog.builder()
                    .type(SyslogType.USER_LOGIN.getValue())
                    .options(SyslogType.USER_LOGIN.getName())
                    .logInfo("用户(" + userProfile.getCurrentUserLoginName() + ")" + SyslogType.USER_LOGIN.getName())
                    .userId(userProfile.getCurrentUserId())
                    .userIp(userProfile.getCurrentUserLoginIp())
                    .build();
            syslogService.insert(syslog);

            //登录信息加入session
            session.setAttribute("userProfile", userProfile);

            resJson = ResponseResult.build(CodeType.SUCCESS, "登录成功！");
            resJson.put("url", url);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            resJson = ResponseResult.build(CodeType.FAIL, "登录失败：系统异常！");
        }
        return resJson;
    }

    /**
     * 执行登出
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/dologout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        //使session失效，从而登出
        session.invalidate();
        return "login";
    }

    /**
     * 修改密码
     *
     * @param request
     * @param oldPwd
     * @param newPwd
     * @param newPwdConfirm
     * @return
     */
    @RequestMapping(value = "/changepwd")
    @ResponseBody
    public JSONObject changepwd(HttpServletRequest request, String oldPwd, String newPwd, String newPwdConfirm) {
        HttpSession session = request.getSession();
        String msg = "success";
        try {
            UserProfile userProfile = (UserProfile) session.getAttribute("userProfile");
            User user = userService.getById(userProfile.getCurrentUserId());
            if (user == null) {
                resJson = ResponseResult.build(CodeType.FAIL, "修改失败：账号不存在！");
                return resJson;
            }
            if (!user.getPassword().equals(EncodeUtil.getPasswordMd5(oldPwd))) {
                resJson = ResponseResult.build(CodeType.FAIL, "修改失败：旧密码错误！");
                return resJson;
            }
            if (oldPwd.equals(newPwd)) {
                resJson = ResponseResult.build(CodeType.FAIL, "修改失败：新密码不能与旧密码相同！");
                return resJson;
            }
            if (!newPwd.equals(newPwdConfirm)) {
                resJson = ResponseResult.build(CodeType.FAIL, "修改失败：确认密码与新密码不一致！");
                return resJson;
            }

            //更新密码并重新登录
            user.setPassword(EncodeUtil.getPasswordMd5(newPwd));
            userService.update(user);
            session.invalidate();

            //添加系统日志
            Syslog syslog = Syslog.builder()
                    .type(SyslogType.CHANGE_PW.getValue())
                    .options(SyslogType.CHANGE_PW.getName())
                    .logInfo("用户(" + userProfile.getCurrentUserLoginName() + ")" + SyslogType.CHANGE_PW.getName())
                    .userId(userProfile.getCurrentUserId())
                    .userIp(userProfile.getCurrentUserLoginIp())
                    .build();
            syslogService.insert(syslog);
            resJson = ResponseResult.build(CodeType.SUCCESS, "修改成功！");
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            resJson = ResponseResult.build(CodeType.FAIL, "修改失败：系统异常！");
        }
        return resJson;
    }
}
